import {Utils} from "../common.js"
import {Module} from "../framework.js"
import * as WidgetEvent from "../widget/widget-event.js"
import D from "../delegator.js"
import * as UI from "../ui.js"

export default class PageTOC extends Module{
    constructor(disp) {
        super(disp);
        this._ui = UI.UIPageTOC();
        this._mapElement = new Map();
        this._enabled = false;


        this.Subscribe(WidgetEvent.EVT_WIDGET_CHANGED_TO_VIEW, event => {
            if(event.changed) {
                this._UpdateTOCForWidget(event.WID, event.element);
            } else {
                this._UnlockWidgetTOC(event.WID);
            }
        });
        this.Subscribe(WidgetEvent.EVT_WIDGET_CHANGED_TO_EDIT, event => {
            this._LockWidgetTOC(event.WID);
        });
        this.Subscribe(WidgetEvent.EVT_WIDGET_ALL_CREATED, event => {
            const _collection = event.collection
            _collection.ForEach((widget) => {
                this._UpdateTOCForWidget(widget.WID, widget.element);
            });
        });
    }
    Update(data) {
        this._enabled = data.toc;
        this._mapElement.clear();
        this._ui.Clear();
    }

    _LockWidgetTOC(WID){
        const _oldElem = this._mapElement.get(WID);
        if (_oldElem) {
            _oldElem.querySelectorAll('a').forEach((el) => {
                D(el).AddClass('slog_disable_a').AddClass('slog_font_red');
            });
        }
    }

    _UnlockWidgetTOC(WID) {
        const _oldElem = this._mapElement.get(WID);
        if (_oldElem) {
            _oldElem.querySelectorAll('a').forEach((el) => {
                D(el).RemoveClass('slog_disable_a').RemoveClass('slog_font_red');
            });
        }
    }

    _UpdateTOCForWidget(WID, element) {
        let _ulElem = undefined;
        if(element) {
            _ulElem = this._ui.GenerateTocElement(element);
        }
        const _oldElem = this._mapElement.get(WID);

        if(_ulElem) {
            if(_oldElem) {
                _oldElem.replaceWith(_ulElem);
            } else {
                this._ui.Add(_ulElem);
            }
            this._mapElement.set(WID, _ulElem);
        }else{
            if(_oldElem) {
                _oldElem.remove();
                this._mapElement.delete(WID);
            }
        }
    }
}

